# from django.contrib.auth.views import login
from django import http
from django.shortcuts import render, redirect
# Create your views here.
from django.urls import reverse
from django.views import View
#注册页面
from apps.users.models import User
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
#判断手机号是否重复注册
class MobileCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})
#判断用户名是否重复注册
class UsernameCountView(View):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})
class RegisterView(View):
    #返回注册页面
    def get(self,request):
        return render(request,"register.html")
    #注册功能
    def post(self,request):
        #接收参数
        username = request.POST.get("username")
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        sms_code = request.POST.get('msg_code')
        #注册用户
        try:
            #保存注册数据
            from apps.users.models import User
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as e:
            logger.info(e)

        #实现状态保持
        from django.contrib.auth import login
        login(request,user)
        #响应注册结果
        response = redirect(reverse("contents:index"))
        return response

